package poem_info;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.jdbc.core.JdbcTemplate;
import poem_info.JdbcUtils.JDBCUtils;

import java.net.URL;
import java.util.List;

/*解析每一首古诗页面的详情信息并保存*/
public class ParseDetailedUrl {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    public void parseUrl(String purl, List<Poem> poemList) throws Exception {
        //定义sql
        String sql = "insert into poems values(null, ?, ?, ?, ?, ?)";
        //创建poem对象
        Poem poem = new Poem();
        //保存purl
        poem.setPurl(purl);
        //解析详情页url
        Document document = null;
        try {
            document = Jsoup.parse(new URL(purl), 100000);
            //获取诗歌名字
            String title = null;
            title = document.select("#sonsyuanwen > div.cont > h1").text();
            poem.setTitle(title);
            //获取作者朝代
            String dynasty = null;
            dynasty = document.select("#sonsyuanwen > div.cont > p > a:nth-child(2)").text().replace("〔", "")
                    .replace("〕", "");
            Integer dynasty_id = new Id().getId(dynasty, 2);
            poem.setDynasty_id(dynasty_id);
            //获取作者姓名
            String writer = null;
            writer = document.select("#sonsyuanwen > div.cont > p > a:nth-child(1)").text();
            Integer writer_id = new Id().getId(writer, 1);
            poem.setWriter_id(writer_id);
            //获取诗歌原文
            String content = null;
            content = document.select("div.contson").first().text();
            poem.setContent(content);
            //如果poem对象以前不存在，再执行
            if(!poemList.contains(poem)) {
                System.out.println("已保存！" + poem.toString());
                poemList.add(poem);
                //存储数据
                template.update(sql, title, dynasty_id, writer_id, content, purl);
            } else {
                System.out.println("已存在！" + poem.toString());
            }
        } catch (Exception e) {
            System.out.println("无法解析！" + poem.toString());
        }
    }
}
